package com.dede.localdex

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

/**
 * 将assets目录下的文件复制到手机存储根目录
 * 开启java进程
 * 查看module locallib
 */
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            if (result != PackageManager.PERMISSION_GRANTED) {
                val arrayOf = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                requestPermissions(arrayOf, 10)
            }
        } else {
            initFile()
        }

        bt_open.setOnClickListener {
            val file = File(getExternalFilesDir(null), fileName)
            if (!file.exists() || !file.isFile || file.length() == 0L) {
                initFile()
                return@setOnClickListener
            }
            dream(file)
        }
        bt_setting.setOnClickListener {
            val intent = Intent(Settings.ACTION_DREAM_SETTINGS)
            startActivity(intent)
            /*screensaver_enabled*/
        }
    }

    private fun dream(file: File) {
        JavaShellUtil.root(true)
        val setClassPath = "export CLASSPATH=${file.absolutePath}"
        val exec = "exec app_process ${file.parentFile.absolutePath} com.dede.locallib.HelloWorld"
        Log.i("test", "onCreate: " + setClassPath)
        Log.i("test", "onCreate: " + exec)
        val commandResult = JavaShellUtil.execCommand(true,
                setClassPath,
                exec)
        Log.i("test", "onCreate: " + commandResult)
    }

//    export CLASSPATH=/storage/emulated/0/Main.dex
//    exec app_process /storage/emulated/0 com.dede.activitylistener.Main

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            initFile()
        }
    }

    private val fileName = "dex.dex"

    private fun initFile() {
        val file = File(getExternalFilesDir(null), fileName)
//        if (file.exists() && file.isFile && file.length() > 0) {
//            return
//        }

        Thread {
            var input: InputStream? = null
            var output: FileOutputStream? = null
            try {
                input = assets.open(fileName)
                output = FileOutputStream(file)
                val bytes = ByteArray(2048)
                var len = input.read(bytes)
                while (len != -1) {
                    output.write(bytes, 0, len)
                    len = input.read(bytes)
                }
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                try {
                    input?.close()
                    output?.close()
                } catch (e: IOException) {
                }
            }
        }.start()
    }
}
